<template>
  <div class="p-2">
    <el-card class="p-2" shadow="never">
      <div class="menu-top">
        <div>
          <el-button type="primary" :loading="buttonLoading" :disabled="pd.form.auditStatus === 2" @click="submitForm"> 保存 </el-button>
          <el-button type="success">复制</el-button>
          <el-button type="danger" @click="handleClose">关闭</el-button>
          <!--约定超过15天后的单据不能作废-->
          <el-button v-if="pd.form.auditStatus === 2" type="danger" :disabled="isVoid < 15" @click="handleVoid">作废</el-button>
        </div>
        <div>
          <el-form ref="warehousingFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
            <el-form-item label="标题" prop="orderNo">
              <el-input v-model="pd.form.orderNo" :disabled="pd.form.auditStatus === 2" placeholder="请输入标题" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div style="border-bottom: 1px solid #eee; margin: 20px -15px" />
      <div>
        <el-form ref="warehousingFormRef" :model="pd.form" :rules="pd.rules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="采购订单" prop="purchaseId">
                <el-input v-model="pd.form.purchaseId" placeholder="请输入采购订单" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="pd.form.supplierId">
                  <el-option v-for="item in supplierList" :key="item.id" :value="item.id" :label="item.name" />
                  <el-option>
                    <SupplierSearch :search-type="0" data-text="选择更多" :params="{ isCustomer: true }" @ok="searchHatch($event)" />
                  </el-option>
                </el-select>
                <!--                <SupplierSearch data-text="供应商" :params="{ isCustomer: true }" @ok="searchHatch($event)" @keyup.enter="handleQuery" />-->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购人员" prop="workerId">
                <el-select v-model="pd.form.workerId" :disabled="pd.form.auditStatus === 2" placeholder="请选择饲养员">
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购日期" prop="buyTime">
                <el-date-picker
                  style="width: 300px"
                  v-model="form.buyTime"
                  clearable
                  type="date"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择采购日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col v-if="pd.form.auditStatus > 1" :span="6">
              <el-form-item label="制单人" prop="createBy">
                <el-select v-model="pd.form.createBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="pd.form.auditStatus > 1" :span="6">
              <el-form-item label="制单时间" prop="createTime">
                <el-input v-model="pd.form.createTime" disabled />
              </el-form-item>
            </el-col>
            <el-col v-if="pd.form.auditStatus > 1" :span="6">
              <el-form-item label="审核时间" prop="auditTime">
                <el-input v-model="pd.form.auditTime" disabled />
              </el-form-item>
            </el-col>
            <el-col v-if="pd.form.auditStatus > 1" :span="6">
              <el-form-item label="审核人" prop="auditBy">
                <el-select v-model="pd.form.auditBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-if="pd.form.auditStatus > 1" :span="6">
              <el-form-item label="单据状态" prop="auditStatus">
                <el-select v-model="pd.form.auditStatus" disabled>
                  <el-option v-for="dict in order_status" :key="dict.value" :value="dict.value" :label="dict.label" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-form-item>
        <ProductsSearch v-if="pd.form.auditStatus != 2" :search-type="2" data-text="新增一行" :params="{ isCustomer: true }" @ok="addLine" />
      </el-form-item>
      <div>
        <el-table
          v-loading="loading"
          border
          :data="pd.form.contentInfo || []"
          :row-class-name="rowClassName"
          :header-cell-style="{ background: 'F1F5FC' }"
          :summary-method="getSummaries"
          show-summary
        >
          <el-table-column prop="xh" width="88" label="序号" align="center">
            <template #default="scope">
              <div class="xh-show">{{ scope.row.xh }}</div>
              <div class="operation_show">
                <el-button :disabled="pd.form.auditStatus === 2" class="button-del" circle size="small" @click="deleteLine(scope.row, scope.$index)">
                  <el-icon>
                    <Minus />
                  </el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-slot="scope" label="商品分类">
            <el-tree-select
              v-model="scope.row.cateId"
              :data="assetCategoryOptions"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              value-key="id"
              filterable
              :render-after-expand="false"
              disabled
            />
          </el-table-column>
          <el-table-column v-slot="scope" label="选择商品">
            <el-select v-model="scope.row.productId" disabled>
              <el-option v-for="item in productsList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
          </el-table-column>
          <el-table-column v-slot="scope" label="商品规格">
            <el-select v-model="scope.row.productSpecId">
              <el-option v-for="item in erpUnitAttrList" :key="item.id" :value="item.id" :label="item.remark" />
            </el-select>
          </el-table-column>
          <el-table-column v-slot="scope" label="当前库存">
            <el-input v-model="scope.row.stock" />
          </el-table-column>
          <el-table-column label="数量" prop="amount">
            <template #default="scope">
              <el-input v-model="scope.row.amount" :disabled="pd.form.auditStatus === 2" placeholder="请输入" @input="computerCostMoney(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column v-slot="scope" label="单价">
            <el-input v-model="scope.row.price" :disabled="pd.form.auditStatus === 2" placeholder="请输入" />
          </el-table-column>
          <el-table-column prop="money" label="金额">
            <template #default="scope">
              <el-input v-model="scope.row.money" :disabled="pd.form.auditStatus === 2" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="position: absolute; margin-top: 10px; right: 30px">
        <el-form ref="warehousingFormRef" :model="pd.form" :rules="pd.rules" inline label-width="100">
          <el-form-item label="总数量:" prop="totalNum">
            <el-input v-model="pd.form.totalNum" :disabled="pd.form.auditStatus === 2" />
          </el-form-item>
          <el-form-item label="总金额:" prop="totalMoney">
            <el-input v-model="pd.form.totalMoney" :disabled="pd.form.auditStatus === 2" />
          </el-form-item>
        </el-form>
      </div>
      <div style="margin-top: 50px">
        <div style="margin-bottom: 10px; display: flex">
          <el-button type="primary" size="small">上传附件</el-button>
          <span style="margin-left: 10px; font-size: 12px; margin-top: 2px">(建议上传附件大小在5M以内)</span>
        </div>
        <el-form ref="warehousingFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="pd.form.remark" type="textarea" rows="3" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="登记人" prop="createBy">
                <el-select v-model="pd.form.createBy" disabled>
                  <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { listUser } from '@/api/system/user';
import type { VNode } from 'vue';
import { listAssetCategory } from '@/api/erp/assetCategory';
import ProductsSearch from '@/views/erp/products/search.vue';
import SupplierSearch from '@/views/erp/supplier/search.vue';
import { listProducts } from '@/api/erp/products';
import { ProductsVO } from '@/api/erp/products/types';
import { listHouse } from '@/api/farm/house';
import { WarehousingForm, WarehousingInfoVO } from '@/api/erp/warehousing/types';
import { addWarehousing, updateWarehousing, defaultTitle, delWarehousingInfo, auditWarehousingApi } from '@/api/erp/warehousing';
import { listErpUnitAttr } from '@/api/erp/erpUnitAttr';
import { ErpUnitAttrVO } from '@/api/erp/erpUnitAttr/types';
import { SupplierVO } from '@/api/erp/supplier/types';
import { listSupplier } from '@/api/erp/supplier';
import dayjs from 'dayjs';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(['closeAdd', 'getList']);
const assetCategoryOptions = ref<AssetCategoryOption[]>([]);
const loading = ref(true); // 按钮状态
const ids = ref<Array<string | number>>([]);
const erpUnitAttrList = ref<ErpUnitAttrVO[]>([]);
const { order_status } = toRefs<any>(proxy?.useDict('order_status'));
const isVoid = ref<number>();
type AssetCategoryOption = {
  id: number;
  name: string;
  children?: AssetCategoryOption[];
};
const props = defineProps({
  rowData: {
    type: Object,
    default: null
  }
});
const auditForm = reactive<any>({
  id: props.rowData.id,
  auditTime: undefined,
  auditStatus: '4',
  auditRemark: undefined
});
const buttonLoading = ref<boolean>(false);
const warehousingFormRef = ref<ElFormInstance>();
const initFormData: WarehousingForm = {
  contentInfo: [],
  id: undefined,
  orderNo: undefined,
  purchaseId: undefined,
  supplierId: undefined,
  totalNum: undefined,
  totalMoney: undefined,
  workerId: undefined,
  buyTime: undefined,
  auditStatus: undefined,
  remark: undefined,
  status: undefined,
  auditTime: undefined,
  auditRemark: undefined,
  auditUserId: undefined
};
const pd = reactive<any>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    houseNum: undefined,
    status: 0,
    params: {}
  },
  unitAttrQueryParams: {
    pageNum: 1,
    pageSize: 10,
    productId: undefined
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    orderId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    cateId: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
    productId: [{ required: true, message: '材料名称不能为空', trigger: 'blur' }],
    amount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
    money: [{ required: true, message: '小计不能为空', trigger: 'blur' }]
  }
});
const { form } = toRefs(pd);

/*获取默认标题*/
const getTitle = async () => {
  let res = await defaultTitle();
  pd.form.orderNo = res.data;
  loading.value = false;
};
watch(
  () => props.rowData,
  () => {
    console.log(props.rowData);
    pd.form = props.rowData;
    loading.value = false;
  }
);

const handleQuery = () => {
  console.log('组件1');
};

/*获取用户列表*/
const userList = ref([]);
const userData = async () => {
  const { rows } = await listUser(null);
  userList.value = rows;
};
/*获取供应商列表*/
const supplierList = ref<SupplierVO[]>([]);
const getSupplier = async () => {
  const res = await listSupplier(pd.queryParams);
  supplierList.value = res.rows;
};
/*获取商品列表*/
const productsList = ref([]);
const getProductsList = async () => {
  const res = await listProducts(null);
  productsList.value = res.rows;
};
/*获取资产类别*/
const getTreeSelect = async () => {
  const res = await listAssetCategory();
  assetCategoryOptions.value = [];
  const data: AssetCategoryOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<AssetCategoryOption>(res.data, 'id', 'parentId');
  assetCategoryOptions.value.push(data);
};
const searchHatch = (vo) => {
  vo.forEach((v) => {
    pd.form.supplierId = v.id;
    return;
  });
};
/*获取规格值列表*/
/** 查询计量单位列表 */
const getUnitAttrList = async () => {
  // loading.value = true;
  const res = await listErpUnitAttr(pd.unitAttrQueryParams);
  console.log(res);
  erpUnitAttrList.value = res.rows;
};

const rowClassName = ({ row, rowIndex }: { row: any; rowIndex: number }) => {
  row.index = rowIndex; // 把每一行的索引放进row
  row.xh = rowIndex + 1;
};

/** 删除行数*/
const deleteLine = async (row: WarehousingInfoVO, $index: any) => {
  const _ids = row?.id || ids.value;
  if (_ids) {
    //如果有ID说明存在数据表里，需请求后台删除
    const { code } = await delWarehousingInfo(_ids);
    if (code === 200) {
      proxy?.$modal.msgSuccess('删除成功');
      pd.form.contentInfo.splice($index, 1);
    }
  } else {
    //未存入的则直接删除
    pd.form.contentInfo.splice($index, 1);
  }
};

/*打开商品列表-选择*/
const addLine = (vo: ProductsVO[]) => {
  vo.forEach((v) => {
    pd.form.contentInfo.push({
      productId: v.id,
      stock: v.stock,
      price: v.price,
      cateId: v.cateId
    });
    pd.unitAttrQueryParams.productId = v.id;
  });
  //执行获取规格值的方法
  getUnitAttrList();
};
/*作废操作*/
/*设置过期时间*/
let a = dayjs(props.rowData.createTime).unix();
let b = dayjs().unix();
isVoid.value = (b - a) / (60 * 60 * 24);

//TODO 超过一定时间后不能将订单作废
const handleVoid = async () => {
  console.log(props.rowData.id);
  await proxy?.$modal.confirm('是否确认将鸡场投喂编号为"' + props.rowData.id + '"的数据作废？').finally();
  let res = await auditWarehousingApi(auditForm);
  if (res.code === 200) {
    proxy?.$modal.msgSuccess('已作废,库存已变更');
    handleClose();
    emit('getList');
  }
};
/** 自定义求和*/
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums: (string | VNode)[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, ['合计']);
      return;
      // 可以根据索引判断是否合计
    } else if (index === 5 || index === 7) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = `${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            let total = prev + curr;
            if (index === 5) {
              pd.form.totalNum = total.toFixed(2);
            } else if (index === 7) {
              pd.form.totalMoney = total.toFixed(2);
            }
            return total;
          } else {
            return prev;
          }
        }, 0)}`;
        return sums[index];
      } else {
        sums[index] = 'N/A';
      }
    }
  });
  return sums;
};

/*表格计算*/
const computerCostMoney = (vo: WarehousingInfoVO) => {
  vo.money = Number((vo.amount! * vo.price!).toFixed(2));
};
/*关闭新增界面*/
const handleClose = () => {
  emit('closeAdd', 1);
};
/** 表单重置 */
const reset = () => {
  pd.form.value = { ...initFormData };
  warehousingFormRef.value?.resetFields();
};
/** 提交按钮 */
const submitForm = () => {
  warehousingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      console.log(pd.form);
      buttonLoading.value = true;
      if (pd.form.id) {
        await updateWarehousing(pd.form).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addWarehousing(pd.form).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('增加成功');
      }
      handleClose();
      emit('getList');
    }
  });
};
onMounted(() => {
  getTitle();
  userData();
  getSupplier();
  getTreeSelect();
  getProductsList();
});
</script>

<style scoped lang="scss">
.menu-top {
  display: flex;
  justify-content: space-between;

  .el-form-item {
    margin-bottom: 0;
  }
}

.button-add {
  color: #3a8ee6;
  font-size: 14px;
}

.button-del {
  color: red;
  font-size: 14px;
}

.xh-show {
  display: block;
}

.operation_show {
  display: none;
}

.el-table__body tr:hover > td .operation_show {
  display: block;
}

.el-table__body tr:hover > td .xh-show {
  display: none;
}
</style>
